package com.linln.admin.shop.controller;

import com.linln.admin.shop.validator.ShopsValid;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.UUIDUtil;
import com.linln.common.vo.JsonResult;
import com.linln.common.vo.PageResult;
import com.linln.common.vo.ResultVo;
import com.linln.modules.shopsService.domain.Shops;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.enums.ConstantEnum;
import com.linln.modules.system.service.UserService;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zsc
 * @date 2020/11/19
 */
@Controller
@RequestMapping("/shopsService/shops")
public class ShopsController {

    @Autowired
    private ShopsService shopsService;

    @Autowired
    private UserService userService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("shopsService:shops:index")
    public String index(Model model, Shops shops,String msg) throws JSONException {
        shops.setDelFlag("0");
        String shopName = shops.getShopName();
        String areaId = shops.getAreaId();
        if(Strings.isBlank(areaId)){
            shops.setAreaId(null);
        }
        if(Strings.isBlank(shopName)){
            shops.setShopName(null);
        }
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("shopName", match -> match.contains()).
                        withMatcher("areaId", match -> match.exact()).
                        withMatcher("delFlag", match -> match.exact());
        // 获取数据列表
        Example<Shops> example = Example.of(shops, matcher);

        Page<Shops> list = shopsService.getPageList(example);

        // 封装数据
        propsDealWith(list.getContent());
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        model.addAttribute("msg", msg);
        model.addAttribute("shopName",shopName);
        model.addAttribute("areaId",areaId);
        return "/shopsService/shops/index";
    }

    private void propsDealWith(List<Shops> content) throws JSONException {
        for(Shops shops : content){
            shops.setShopTypeName((String) shops.getPropsJson().get("shopTypeName"));
        }
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("shopsService:shops:add")
    public String toAdd() {
        return "/shopsService/shops/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("shopsService:shops:edit")
    public String toEdit(@PathVariable("id") Shops shops, Model model) {
        model.addAttribute("shops", shops);
        return "/shopsService/shops/add";
    }

    @GetMapping("/editShopDetails/{id}")
    @RequiresPermissions("shopsService:shops:editShopDetails")
    public String toEditShopDetails(@PathVariable("id") Shops shops, Model model) {
        model.addAttribute("shops", shops);
        return "/shopsService/shops/editShopDetails";
    }
    /**
     * 保存添加/修改的数据
     *
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"shopsService:shops:add", "shopsService:shops:edit"})
    @ResponseBody
    public ResultVo save(@Validated ShopsValid valid, String shopTypeName, Shops shops , MultipartFile file) throws JSONException {
        //添加还是修改
        Boolean flag = false;
        //逻辑删除
        shops.setDelFlag("0");
        shops.setAuditMark("1");
        //扩展字段
        if(Strings.isNotBlank(shopTypeName)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("shopTypeName",shopTypeName);
            shops.setProps(jsonObject.toString());
        }
        // 复制保留无需修改的数据
        if (shops.getShopId() != null) {
            Shops beShops = shopsService.getById(shops.getShopId());
            EntityBeanUtil.copyProperties(beShops, shops);
            flag = true;
        }else {
            //没有id就代表新建
            shops.setShopId(UUIDUtil.randomUUID32());
            //创建日期时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            Date now = new Date();
            String time = sdf.format(now);
            shops.setScore(5.0);
            shops.setCreateDate(time);
        }
        // 保存数据
        try {
            Long userid = Strings.isBlank(valid.getUserId())?null:Long.valueOf(valid.getUserId());
            shopsService.save(shops,userid,file,flag);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVoUtil.error(Strings.isBlank(e.getMessage())?ConstantEnum.SAVEFAIL.getName():e.getMessage());
        }
        return ResultVoUtil.SAVE_SUCCESS;
    }

    @ResponseBody
    @GetMapping("delete/{shopId}")
    public ResultVo deleteShop(@PathVariable("shopId") String shopId){
        try {
            shopsService.deleteShop(shopId);
        } catch (Exception e){
            e.printStackTrace();
            return ResultVoUtil.error(Strings.isBlank(e.getMessage())?ConstantEnum.DELFAIL.getName():e.getMessage());
        }
        return ResultVoUtil.success(ConstantEnum.DELSUCCESS.getName());
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("shopsService:shops:detail")
    public String toDetail(@PathVariable("id") Shops shops, Model model) throws JSONException {
        JSONObject jsonObject = new JSONObject(Strings.isBlank(shops.getProps())?"{}":shops.getProps());
        model.addAttribute("shops",shops);
        if(jsonObject.isNull("shopTypeName")){
            model.addAttribute("shopTypeName",shops.getShopType());
        }else {
            model.addAttribute("shopTypeName",jsonObject.get("shopTypeName"));
        }
        return "/shopsService/shops/detail";
    }

    /** 跳转关联用户页面
     * @param shopsId
     * @param model
     * @return
     */
    @GetMapping("/relatedUser/{id}")
    @RequiresPermissions("shopsService:shops:relatedUser")
    public String relatedUser(@PathVariable("id") String shopsId, Model model){
        model.addAttribute("shopsId",shopsId);
        return "/shopsService/shops/relatedUser";
    }


    /**
     * 搜索手机用户
     * @param phone
     * @return
     */
    @GetMapping("/searchUser")
    @RequiresPermissions("shopsService:shops:searchUser")
    @ResponseBody
    public PageResult<User> searchUser(String phone){
        List<User> userList = new ArrayList<>();
        userList.add(shopsService.getByPhone(phone));
        return new PageResult<>(userList,1);
    }

    /**
     * 添加店铺店员
     * @param shopsId
     * @param userId
     * @return
     */
    @PostMapping("/addShopUser")
    @RequiresPermissions("shopsService:shops:addShopUser")
    @ResponseBody
    public JsonResult addShopUser(String shopsId,Long userId){
        return shopsService.addShopUser(shopsId,userId);
    }

    /**
     * 删除店铺用户
     * @param shopUserId
     * @param userId
     * @return
     */
    @PostMapping("/delShopUser")
    @RequiresPermissions("shopsService:shops:delShopUser")
    @ResponseBody
    public JsonResult delShopUser(String shopUserId,Long userId){
        try {
            shopsService.delShopUser(shopUserId,userId);
            return JsonResult.ok();
        }catch (Exception e){
            return JsonResult.error();
        }
    }
    /**
     * 店铺人员列表
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/shopUser")
    @RequiresPermissions("shopsService:shops:shopUser")
    @ResponseBody
    public PageResult<Map<String,String>> shopUser(Integer page, Integer limit,String shopsId){
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 5;
        }
        return shopsService.shopUserPage((page-1)*limit,limit,shopsId);
    }


    /**
     *  更具id获取子节点信息
     * @param parentId
     * @return
     */
    @ResponseBody
    @GetMapping("/getAreaData/{parentId}")
    public JsonResult getAreaData(@PathVariable("parentId")String parentId){
        return JsonResult.ok().put("data",shopsService.getAreaData(parentId,""));
    }

    /**
     * 更具id获取位置信息
     * @param areaId
     * @return
     */
    @ResponseBody
    @GetMapping("/getMyAreaData/{areaId}")
    public JsonResult getMyAreaData(@PathVariable("areaId")String areaId){
        return JsonResult.ok().put("data",shopsService.getAreaData("",areaId));
    }

    /**
     *获取店长
     * @param shopId
     * @return
     */
    @ResponseBody
    @GetMapping("/getManager/{shopId}")
    public JsonResult getManager(@PathVariable("shopId")String shopId){
        return JsonResult.ok().put("data",shopsService.getManager(shopId, Long.valueOf(ConstantEnum.STOREMANAGER.getValue())));
    }

    @ResponseBody
    @GetMapping("/getShopType")
    public JsonResult getShopType(){
        List<Map<String,Object>> mapList =  shopsService.getShopType();
        return JsonResult.ok().put("data",mapList);
    }

    @ResponseBody
    @PostMapping("/saveShopDetails")
    public JsonResult saveShopDetails(String shopId , String shopDetails) throws UnsupportedEncodingException {
        Shops shops = shopsService.getById(shopId);
        String html = URLDecoder.decode(shopDetails, "UTF-8");
        shops.setShopDetails(html);
        shopsService.saveShopDetails(shops);
        return JsonResult.ok("保存成功");
    }
}
